//
//  CJEditFirmController.m
//  Boss
//
//  Created by admin on 2018/9/15.
//  Copyright © 2018年 admin. All rights reserved.
//

#import "CJEditFirmController.h"
#import "WYEditSectionView.h"
#import "WYProductCell.h"
#import "WYHonorCell.h"
#import "CJEditCompanyMessageCell.h"
#import "CJEditCompanyHeaderCell.h"
#import "WYUploadModel.h"
#import "UIImage+WYSaveImage.h"
#import "CJEditFirmMessageController.h"
#import "WYIndustryController.h"
#import "CJAddFirmProductController.h"
#import "CJProductDetailController.h"
@interface CJEditFirmController ()<UITableViewDelegate,UITableViewDataSource,WYEditSectionViewDelegate,WYHonorCellDelegate,CJEditCompanyMessageCellDelegate,CJEditCompanyHeaderCellDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic,strong)UITableView *tableView;

@property (nonatomic,strong)NSString *pathString;

@property (nonatomic,strong)WYUploadModel *uploadNodel;

@property (nonatomic,assign)NSUInteger index;

@end

@implementation CJEditFirmController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    
    // Do any additional setup after loading the view.
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self loadData];
}
-(void)loadData
{
    
    WEAKSELF
    
    [WYHttpServer getMyFirmStatusSucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        
        if (success) {
            weakSelf.model = [CJCompanyModel getCompanyModelFromJson:response[@"result"]];
            [weakSelf.tableView reloadData];
        }
    }];
    
    
    
}



-(void)setupUI
{
    [self.view addSubview:self.tableView];
    self.navigationItem.title = @"编辑企业主页";
    [self.tableView registerNib:[UINib nibWithNibName:@"CJEditCompanyMessageCell" bundle:nil] forCellReuseIdentifier:@"CJEditCompanyMessageCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"WYHonorCell" bundle:nil] forCellReuseIdentifier:@"WYHonorCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"WYProductCell" bundle:nil] forCellReuseIdentifier:@"WYProductCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"CJEditCompanyHeaderCell" bundle:nil] forCellReuseIdentifier:@"CJEditCompanyHeaderCell"];
    self.tableView.estimatedRowHeight = 100;
    
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==3) {
        return self.model.firmProduct.count;
    }
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        CJEditCompanyHeaderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CJEditCompanyHeaderCell" forIndexPath:indexPath];
        
        if (!cell) {
            cell = [[NSBundle mainBundle]loadNibNamed:@"CJEditCompanyHeaderCell" owner:nil options:nil].firstObject;
        }
        
        [cell.companyImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@!default",self.model.firm.firmLogo]] placeholderImage:nil];
        
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.delegate = self;
        return cell;
    }
    if (indexPath.section ==1) {
        CJEditCompanyMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CJEditCompanyMessageCell" forIndexPath:indexPath];
        if (!cell) {
            cell = [[NSBundle mainBundle]loadNibNamed:@"CJEditCompanyMessageCell" owner:nil options:nil].firstObject;
        }
        [cell setFirmModel:self.model.firm];
        cell.delegate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    if (indexPath.section ==2) {
        WYHonorCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WYHonorCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.dataArray = self.model.firmHonor.mutableCopy;
        cell.delegate = self;
        return cell;
    }
    if (indexPath.section ==3) {
        WYProductCell *cell =[tableView dequeueReusableCellWithIdentifier:@"WYProductCell" forIndexPath:indexPath];
        if (!cell) {
            cell =[[NSBundle mainBundle]loadNibNamed:@"WYProductCell" owner:nil options:nil].firstObject;
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        //        WYProductService *service = self.dataArray[indexPath.row];
        //        [cell setService:service];
        CJFirmProductModel *model = self.model.firmProduct[indexPath.row];
        [cell setModel:model];
        return cell;
    }
    
    
    
    return nil;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section==3) {
        CJFirmProductModel *model = self.model.firmProduct[indexPath.row];
        
        CJProductDetailController *pdc = [[CJProductDetailController alloc]init];
        pdc.model = model;
        [self.navigationController pushViewController:pdc animated:YES];
        
        
    }
    
    
    
    
}






-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        return 0.00001;
    }
    if (section==1) {
        return 0;
    }
    if (section==2) {
        return 50;
    }
    if (section==3) {
        return 50;
    }
    return 10;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section==2) {
        WYEditSectionView *esc = [[WYEditSectionView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
        esc.index = 3;
        esc.delegate = self;
        esc.backgroundColor = [UIColor whiteColor];
        //        if (self.honorArray.count) {
        //            esc.lineView.hidden = YES;
        //        }
        return esc;
        
    }
    if (section==3) {
        WYEditSectionView *esc = [[WYEditSectionView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
        esc.delegate = self;
        esc.index = 4;
        esc.backgroundColor = [UIColor whiteColor];
        //        if (self.dataArray.count) {
        //            esc.lineView.hidden = YES;
        //        }
        return esc;
    }
    
    
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = kColore2e2e2;
    return view;
}

- (void)didSelectAddButton:(NSUInteger)index WithBtn:(UIButton *)btn
{
    if (index==3) {
        self.index =3;
        [self showPicker];
    }
    if (index==4) {
        CJAddFirmProductController *afc = [[CJAddFirmProductController alloc]init];
        [self.navigationController pushViewController:afc animated:YES];
    }
    
    
    
}



-(void)editCompanyImageView:(NSString *)brandName
{
    self.index = 0;
    [self showPicker];
    
    
    
}

-(void)showPicker
{
    
    WEAKSELF
    
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self; //设置代理
    imagePickerController.allowsEditing = YES;
    
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [weakSelf presentViewController:imagePickerController animated:YES completion:nil];
    }];
    
    
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [weakSelf presentViewController:imagePickerController animated:YES completion:nil];
    }];
    [alertController addAction:action1];
    [alertController addAction:action2];
    [alertController addAction:action3];
    if (IS_IPAD) {
        //        UIPopoverPresentationController *popPresenter = [alertController popoverPresentationController];
        //        popPresenter.sourceView = cell;
        //        popPresenter.sourceRect = cell.bounds;
        //        [self presentViewController:alertController animated:YES completion:nil];
        
    }else{
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{}];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    //[self showLoading:@""];
    [picker dismissViewControllerAnimated:YES completion:^{}];
    UIImage *photo = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    NSString *path = [photo QCloudTempFilePathWithExtension:@"PNG"];
    self.pathString = path;
    [UIImagePNGRepresentation(photo) writeToFile:path atomically:YES];
    
    [self showLoading:@""];
    
    WEAKSELF
    [WYHttpServer uploadImageSucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        WYUploadModel *model = [WYUploadModel getupLoadModelFromJson:response[@"result"]];
        [weakSelf upLoadWithPath:model.uploadUrl];
        weakSelf.uploadNodel = model;
    }];
}
-(void)upLoadWithPath:(NSString *)path
{
    WEAKSELF
    [WYHttpServer PUTWithURLStr:path filePath:self.pathString SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // UI更新代码
            [weakSelf hideLoading];
        });
        if (success) {
            if (self.index ==0) {
                [weakSelf editHeaderImageview];
            }else{
                [weakSelf addHonor];
            }
            
        }else{
            [weakSelf toast:errorMessage];
        }
    }];
}
-(void)addHonor
{
    WEAKSELF
    [WYHttpServer insertFirmHonorWithUrl:self.uploadNodel.visitUrl SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                // UI更新代码
//                 [weakSelf toast:@"添加成功"];
//            });
           
            [weakSelf loadData];
        }else{
            [weakSelf toast:errorMessage];
        }
        
        
        
        
    }];
    
    
    
}
-(void)editHeaderImageview
{
    [WYHttpServer editMyFirmWithBrandName:nil WithFirmIntroduction:nil WithFirmType:nil WithFirmLogo:self.uploadNodel.visitUrl SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        
        if (success) {
            [self loadData];
        }
        
    }];
}








-(void)clickIndustryActionWithIndustryName:(NSString *)industryName
{
    WYIndustryController *idc = [[WYIndustryController alloc]init];
    [self.navigationController pushViewController:idc animated:YES];
}
-(void)clickCompanyNameWithCompanyName:(NSString *)companyName
{
    CJEditFirmMessageController *efc = [[CJEditFirmMessageController alloc]init];
    efc.placeHoder = @"请输入公司介绍";
    efc.textString = self.model.firm.firmIntroduction;
    efc.navTitle = @"公司介绍";
    efc.tag = 2;
    [self.navigationController pushViewController:efc animated:YES];
}
-(void)clickBrandActionWithBrandName:(NSString *)brandName
{
    CJEditFirmMessageController *efc = [[CJEditFirmMessageController alloc]init];
    efc.placeHoder = @"请输入品牌名称";
    efc.textString = self.model.firm.brandName;
    efc.navTitle = @"品牌名称";
    efc.tag = 1;
    
    [self.navigationController pushViewController:efc animated:YES];
    
}

- (UITableView *)tableView
{
    if (_tableView == nil) {
        CGRect frame = CGRectMake(0, self.navHeight, kScreenWidth, kScreenHeight-self.navHeight);
        _tableView = [[UITableView alloc] initWithFrame:frame
                                                  style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView setSeparatorStyle:(UITableViewCellSeparatorStyleNone)];
    }
    return _tableView;
}


@end
